using System;
using System.Threading.Tasks;

namespace Framework.Extensions
{
    public static class TaskExtensions
    {
        public static Task<TRes> ThenUsing<T, TRes>(
            this Task<T> source,
            Func<T, TRes> action,
            Func<Exception, TRes> onError)
            where T : IDisposable
        {
            return source.ContinueWith(t =>
            {
                if (t.Exception != null)
                    return onError(t.Exception);
                else
                    try
                    {
                        using (var res = t.Result)
                            return action(res);
                    }
                    catch (Exception ex)
                    {
                        return onError(ex);
                    }
            });
        }

    }
}